<template>
  <TopArea @button-click="handleButtonClickReult"
   @theme-changed-to-parent="handleThemeUpdate"
   :AMap="AMap"
   :map="map"
   />
  <div id="map"></div>
</template>

<script setup>
import { ref,onMounted } from 'vue';
import TopArea from '@/components/TopArea.vue';
import AMapLoader from '@amap/amap-jsapi-loader';
import axios from 'axios';
window._AMapSecurityConfig = {
  securityJsCode: "f73f4bf5ce6cdb661081e1e1c3205161",
};

const map = ref(null);
const AMap = ref(null);
let satellite = null;
let roadNet = null;
let layers = [];
let traffic = null;
let mouseTool = null;
const isCeju = ref(false);
//实例化控件方便后续隐藏
let toolBar;
let scale;
let controlBar;
// 空气质量API配置
const AIR_API_KEY = '5371289c402ac9b6b1c5b7f429aee115'; 
const airMarkers = ref([]); // 存储空气质量标记

const handleButtonClickReult = (buttonType,currentCity) => {
  switch(buttonType){
    case 'weixing':
      toggleSatelliteLayer();
      break;
    case 'luwangLayer':
      addLuwangLayer();
      break;
    case 'kongqi':
      showAirQualityData(currentCity);
      break;
    case 'lukuang':
      addLukuangLayer();
      break;
    case 'ceju':
      addCeju();
      break;
    case 'quanping':
      hideControls();
      break;
    case 'exitQuanping':
      showControls();
      break;
    default:
      console.warn(`未知按钮类型: ${buttonType}`);
  }
}

const toggleSatelliteLayer = () =>{
  //获取最新的图层数组
  const currentLayers = map.value.getLayers();
  if(currentLayers.find(layer => layer.CLASS_NAME === 'AMap.TileLayer.RoadNet') || currentLayers.find(layer => layer.CLASS_NAME === 'AMap.TileLayer.Satellite')) {
    map.value.remove(satellite)
    map.value.remove(roadNet)
  } else {
  map.value.add(satellite);
  map.value.add(roadNet);
}
}

const addLuwangLayer = () => {
  //查找是否有了路网图层
  layers = map.value.getLayers();
  const existLuwang = layers.find(layer => layer.CLASS_NAME === 'AMap.TileLayer.RoadNet')
  if(existLuwang) {
    map.value.remove(roadNet)
  } else {
    map.value.add(roadNet)
  }
}

const showAirQualityData = (currentCity) =>{
  if(airMarkers.length > 0) {
  clearAirMarkers();
  return;
  }
  console.log(currentCity);//能获取到
   // 获取数据并创建标记
  fetchAirQuality(currentCity).then(data => {
    if (!data) return;
    
    const stations = data[0].lastMoniData;
    const stationList = Array.isArray(stations)?stations:Object.values(stations)

     // 过滤掉无效坐标的监测站
    const validStations = stationList.filter(station => {
      return station && 
             station.city && 
             station.AQI !== undefined && 
             station.lon && station.lat &&  // 确保经纬度存在
             !isNaN(parseFloat(station.lon)) && // 确保能转换为数字
             !isNaN(parseFloat(station.lat));
    });

    validStations.forEach(station => {
      const content = `<div class="air-station-marker">
      <span>${station.city}</span><span class="AQI">${station.AQI}</span>
      </div>`
      //数据中有些站点经纬度为null或者空
      const airStationMarker = new AMap.value.Marker({
        content:content,//自定义点标记覆盖物的内容
        position:[parseFloat(station.lon),parseFloat(station.lat)],//需要接收数字，不能时字符串
      })
      map.value.add(airStationMarker);
      airMarkers.value.push(airStationMarker);//存进marker数组中，方便删除
    })
    if(stationList.length > 0) {
      map.value.setFitView();
    }
  })
}

// 获取城市空气质量数据
async function fetchAirQuality(cityName) {
  try {
    const response = await axios.get('https://web.juhe.cn/environment/air/cityair', {
      params: {
        key: AIR_API_KEY,
        city: cityName
      }
    });
    
    if (response.data.error_code !== 0) {
      throw new Error(response.data.reason);
    }
    
    return response.data.result;
    
  } catch (error) {
    console.error('获取空气质量数据失败:', error);
    return null;
  }
}

// 清除所有空气质量标记
function clearAirMarkers() {
  airMarkers.value.forEach(marker => {
    map.value.remove(marker);
  });
  airMarkers.value = [];
}

const addLukuangLayer = () => {
  //查找是否有利路况图层
  layers = map.value.getLayers();//写在函数里面，更新图层信息
  const existLukuang = layers.find(layer => layer.CLASS_NAME === 'AMap.TileLayer.Traffic')
  if(existLukuang) {
    map.value.remove(traffic)
  } else {
    map.value.add(traffic)
  }
}

const addCeju = () => {
  if(isCeju.value) {
    mouseTool.close(false);
    isCeju.value = false;
  } else {
  //在插件的回调函数中使用功能 
  isCeju.value = true;
mouseTool.rule({
  startMarkerOptions: { //设置量测起始点标记属性对象 可缺省   
    icon: new AMap.value.Icon({
      size: new AMap.value.Size(19, 31), //图标大小
      imageSize: new AMap.value.Size(19, 31), 
      image: "//webapi.amap.com/theme/v1.3/markers/b/start.png",
    }),
    offset: new AMap.value.Pixel(-9, -31),
  },
  endMarkerOptions: { //设置量测结束点标记属性对象 可缺省  
    icon: new AMap.value.Icon({
      size: new AMap.value.Size(19, 31), //图标大小
      imageSize: new AMap.value.Size(19, 31),
      image: "//webapi.amap.com/theme/v1.3/markers/b/end.png",
    }),
    offset: new AMap.value.Pixel(-9, -31),
  },
  midMarkerOptions: { //设置拖拽路线插件途经点点标记属性对象 可缺省
    icon: new AMap.value.Icon({
      size: new AMap.value.Size(19, 31), //图标大小
      imageSize: new AMap.value.Size(19, 31),
      image: "//webapi.amap.com/theme/v1.3/markers/b/mid.png",
    }),
    offset: new AMap.value.Pixel(-9, -31),
  },
  lineOptions: { //可缺省
    strokeStyle: "solid",
    strokeColor: "#FF33FF",
    strokeOpacity: 1,
    strokeWeight: 2,
  },
});
  }
}

const handleThemeUpdate = (theme) => {
  switch (theme) {
    case 'biaozhun':
      map.value.setMapStyle("amap://styles/normal");
      break;
    case 'blue':
      map.value.setMapStyle("amap://styles/blue")
      break;
    case 'black':
      map.value.setMapStyle("amap://styles/dark")
      break;
    default:
      console.log('底图未知类型')
      break;
  }
}

const hideControls = () => {
  toolBar.hide();
  scale.hide();
  controlBar.hide();
}

const showControls = () => {
  toolBar.show();
  scale.show();
  controlBar.show();
}

const initMap = async() => {
AMap.value = await AMapLoader.load({
  key: "203876b728fb9aaff3383e31ef8f0675",
  version: "2.0", 
  plugins:["AMap.ToolBar","AMap.Scale","AMap.ControlBar","AMap.Geolocation","AMap.MouseTool"]
});
map.value = new AMap.value.Map('map',{
  viewMode:'3D',
  zoom:17,
  // center:[112.92,27.9]
  //不设置center高德地图会自动定位
});
toolBar = new AMap.value.ToolBar();
scale = new AMap.value.Scale();
controlBar = new AMap.value.ControlBar({
  position:{
    //控件大小只能通过CSS来调整
    bottom:"140px",
    right:"-10px",
  }
})
map.value.addControl(toolBar)
map.value.addControl(scale)
map.value.addControl(controlBar)
map.value.addControl(new AMap.value.Geolocation({
  position:{
    bottom:"100px",
    right:"20px",
  }
}))
//卫星图层和路网图层
satellite = new AMap.value.TileLayer.Satellite();
roadNet = new AMap.value.TileLayer.RoadNet();

//创建实时交通图层（路况）
traffic = new AMap.value.TileLayer.Traffic({
  autoRefresh:true,
  interval:180,
})

  mouseTool = new AMap.value.MouseTool(map.value);
  //创建鼠标工具实例
}

onMounted(() =>{
  initMap();
})

</script>

<style lang="scss" scoped>
#map {
  width: 100vw;
  height: 100vh;
}
.air-station-marker{
  /* 空气站点样式 */
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-radius: 25% 25% 25% 0;
  border: 2px solid black;
  span{
    width: 50px;
    height: 30px;
    text-align: center;
  }
  span.AQI{
    background-color: green;
    color: white;
  }
}
</style>